// 微积分计算模块
class CalculusEngine {
    constructor() {
        this.parser = math.parser();
    }

    // 设置函数
    setFunction(expr) {
        try {
            this.parser.clear();
            this.parser.evaluate(`f(x) = ${expr}`);
            this.functionExpr = expr;
            return true;
        } catch (error) {
            console.error('函数解析错误:', error);
            return false;
        }
    }

    // 计算函数值
    evaluate(x) {
        try {
            return this.parser.evaluate(`f(${x})`);
        } catch (error) {
            return NaN;
        }
    }

    // 计算极限
    calculateLimit(point, direction = 'both') {
        const h = 0.0001;
        let leftLimit, rightLimit;

        try {
            if (direction === 'left' || direction === 'both') {
                leftLimit = this.evaluate(point - h);
            }
            if (direction === 'right' || direction === 'both') {
                rightLimit = this.evaluate(point + h);
            }

            if (direction === 'left') return leftLimit;
            if (direction === 'right') return rightLimit;
            
            // 检查左右极限是否相等
            if (Math.abs(leftLimit - rightLimit) < 0.001) {
                return (leftLimit + rightLimit) / 2;
            }
            return null;
        } catch (error) {
            return null;
        }
    }

    // 计算导数（数值方法）
    calculateDerivative(x, h = 0.0001) {
        try {
            const f1 = this.evaluate(x + h);
            const f2 = this.evaluate(x - h);
            return (f1 - f2) / (2 * h);
        } catch (error) {
            return NaN;
        }
    }

    // 计算定积分（梯形法则）
    calculateIntegral(a, b, n = 1000) {
        try {
            const h = (b - a) / n;
            let sum = 0;
            
            for (let i = 0; i < n; i++) {
                const x0 = a + i * h;
                const x1 = a + (i + 1) * h;
                const y0 = this.evaluate(x0);
                const y1 = this.evaluate(x1);
                
                if (isNaN(y0) || isNaN(y1)) continue;
                
                sum += (y0 + y1) * h / 2;
            }
            
            return sum;
        } catch (error) {
            return NaN;
        }
    }

    // 泰勒展开
    calculateTaylorSeries(center, order = 5) {
        try {
            const terms = [];
            let currentDerivative = this.functionExpr;
            
            for (let n = 0; n <= order; n++) {
                if (n === 0) {
                    const value = this.evaluate(center);
                    terms.push({
                        coefficient: value,
                        power: n,
                        term: `${value}`
                    });
                } else {
                    // 使用数值导数
                    const h = 0.0001;
                    let derivative = 0;
                    
                    // 计算n阶导数在center点的值
                    let currentValue = this.evaluate(center);
                    let prevValue = currentValue;
                    
                    for (let k = 0; k < n; k++) {
                        const f1 = this.evaluate(center + h);
                        const f2 = this.evaluate(center - h);
                        derivative = (f1 - f2) / (2 * h);
                    }
                    
                    const coefficient = derivative / this.factorial(n);
                    terms.push({
                        coefficient: coefficient,
                        power: n,
                        term: `${coefficient > 0 ? '+' : ''}${coefficient.toFixed(4)}(x-${center})^${n}`
                    });
                }
            }
            
            return terms;
        } catch (error) {
            return [];
        }
    }

    // 阶乘计算
    factorial(n) {
        if (n <= 1) return 1;
        let result = 1;
        for (let i = 2; i <= n; i++) {
            result *= i;
        }
        return result;
    }

    // 生成函数数据点
    generateData(start, end, step = 0.1) {
        const data = [];
        for (let x = start; x <= end; x += step) {
            const y = this.evaluate(x);
            if (!isNaN(y) && isFinite(y)) {
                data.push({ x, y });
            }
        }
        return data;
    }

    // 生成导数数据点
    generateDerivativeData(start, end, step = 0.1) {
        const data = [];
        for (let x = start; x <= end; x += step) {
            const y = this.calculateDerivative(x);
            if (!isNaN(y) && isFinite(y)) {
                data.push({ x, y });
            }
        }
        return data;
    }

    // 生成积分区域数据
    generateIntegralArea(a, b, n = 100) {
        const data = [];
        const h = (b - a) / n;
        
        for (let i = 0; i <= n; i++) {
            const x = a + i * h;
            const y = this.evaluate(x);
            if (!isNaN(y) && isFinite(y)) {
                data.push({ x, y });
            }
        }
        
        return data;
    }
}

// 数学公式格式化
function formatFormula(formula) {
    return `\\(${formula}\\)`;
}

// 导出给全局使用
window.CalculusEngine = CalculusEngine;
